package cn.yoline.xylink.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.ainemo.sdk.otf.ConnectNemoCallback;
import com.ainemo.sdk.otf.LoginResponseData;
import com.ainemo.sdk.otf.MakeCallResponse;
import com.ainemo.sdk.otf.NemoSDK;
import com.ainemo.sdk.otf.VideoConfig;
import com.tbruyelle.rxpermissions2.RxPermissions;

import cn.yoline.xylink.R;
import cn.yoline.xylink.XylinkStore;
import cn.yoline.xylink.constant.MeetingConstant;

/**
 * Copyright 2020 JxGIS
 *
 * @file EntryMeetingActivity
 * @auth linaisheng
 * Created on 2022/7/27.
 * Description：
 */
public class EntryMeetingActivity extends BaseActivity {

    private String mCallNumber;
    private String numberPwd;
    private String meetingRoomName;

    private String userName;
    private String userId;

    private RxPermissions rxPermissions;
    private XylinkStore xylinkStore = XylinkStore.getInstant();

    private TextView tvIncomingNumber;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Window win = getWindow();
        win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
        win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
        setContentView(R.layout.activity_meeting_entry_call);

        xylinkStore.setIsOnMeeting(true);
        tvIncomingNumber = findViewById(R.id.incoming_number);
        findViewById(R.id.incoming_hangup).setOnClickListener(view -> {
            xylinkStore.setIsOnMeeting(false);
            finish();
        });

        initData();
    }


    private void initData() {
        Intent intent = getIntent();
        mCallNumber = intent.getStringExtra(MeetingConstant.CALL_NUMBER);
        numberPwd = intent.getStringExtra(MeetingConstant.CALL_NUMBER_PWD);

        meetingRoomName = intent.getStringExtra(MeetingConstant.MEETING_ROOM_NAME);
        if (intent.hasExtra(MeetingConstant.MEETING_ROOM_VIDEO_CONFIG)) {
            String videoConfig = intent.getStringExtra(MeetingConstant.MEETING_ROOM_VIDEO_CONFIG);
            if (VideoConfig.VD_320x180.equals(videoConfig)) {
                NemoSDK.getInstance().setVideoConfiguration(VideoConfig.VD_320x180);
            } else if (VideoConfig.VD_640x360.equals(videoConfig)) {
                NemoSDK.getInstance().setVideoConfiguration(VideoConfig.VD_640x360);
            } else if (VideoConfig.VD_1280x720.equals(videoConfig)) {
                NemoSDK.getInstance().setVideoConfiguration(VideoConfig.VD_1280x720);
            } else {
                NemoSDK.getInstance().setVideoConfiguration(VideoConfig.VD_1280x720);
            }
        }

        userId = intent.getStringExtra(MeetingConstant.USER_ID);
        userName = intent.getStringExtra(MeetingConstant.USER_NAME);

        if (isEmpty(mCallNumber)) {
            showToast("号码为空");
            finish();
            return;
        } else if (isEmpty(userId)) {
            showToast("用户id为空");
            finish();
            return;
        }  else if (isEmpty(userName)) {
            showToast("用户名为空");
            finish();
            return;
        }
        if (TextUtils.isEmpty(meetingRoomName)) {
            tvIncomingNumber.setText(mCallNumber);
        } else {
            tvIncomingNumber.setText(meetingRoomName);
        }


        if (userName.contains("-")) {
            userName = userName.replace("-", "");
        }
        try {
            NemoSDK nemoSDK = NemoSDK.getInstance();
            nemoSDK.loginExternalAccount(userName, userId, new ConnectNemoCallback() {

                @Override
                public void onFailed(String code) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showToast("会议登录失败");
                            finish();
                        }
                    });

                }

                @Override
                public void onSuccess(LoginResponseData loginResponseData, boolean b) {
                    XylinkStore.getInstant().setTokenInfo(loginResponseData.getTokenInfo());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            checkPermission();
                        }
                    });
                }

                @Override
                public void onNetworkTopologyDetectionFinished(LoginResponseData loginResponseData) {

                }
            });
        } catch (Exception e) {
            showToast("会议登录失败");
            finish();
        }
    }

    @SuppressLint("CheckResult")
    private void checkPermission() {
        rxPermissions = new RxPermissions(this);
        if (rxPermissions.isGranted(Manifest.permission.CAMERA)
                && rxPermissions.isGranted(Manifest.permission.RECORD_AUDIO)) {
            jointMeeting();
        } else {
            rxPermissions.request(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO)
                    .subscribe(aBoolean -> {
                        if (aBoolean) {
                            jointMeeting();
                        } else {
                            showToast("未授权权限");
                            finish();
                        }
                    });
        }
    }


    private void jointMeeting() {
        NemoSDK.getInstance().makeCall(mCallNumber, !isEmpty(numberPwd) ? numberPwd : "",
                new MakeCallResponse() {
                    @Override
                    public void onCallSuccess() {
                        // 查询号码成功, 进入通话界面
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                xylinkStore.setIsOnMeeting(true);
                                startActivity(MeetingRoomActivity.getStartIntent(
                                        EntryMeetingActivity.this,
                                        mCallNumber, meetingRoomName));
                                finish();
                            }
                        });
                    }

                    @Override
                    public void onCallFail(String error, String msg) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showToast("加入会议失败：" + error);
                            }
                        });
                    }
                });
    }


    @Override
    public void onBackPressed() {
        xylinkStore.setIsOnMeeting(false);
        finish();
    }

    private void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    private boolean isEmpty(final CharSequence s) {
        return s == null || s.length() == 0;
    }

    public static Intent getStartIntent(
            Context context, String callNumber, String numberPwd,
            String userId, String userName) {
        Intent intent = new Intent(context, EntryMeetingActivity.class);
        intent.putExtra(MeetingConstant.CALL_NUMBER, callNumber);
        intent.putExtra(MeetingConstant.CALL_NUMBER_PWD, numberPwd);

        intent.putExtra(MeetingConstant.USER_ID, userId);
        intent.putExtra(MeetingConstant.USER_NAME, userName);
        return intent;
    }

    public static Intent getStartIntent(
            Context context, String callNumber, String numberPwd,
            String userId, String userName, String videoConfig) {
        Intent intent = new Intent(context, EntryMeetingActivity.class);
        intent.putExtra(MeetingConstant.CALL_NUMBER, callNumber);
        intent.putExtra(MeetingConstant.CALL_NUMBER_PWD, numberPwd);

        intent.putExtra(MeetingConstant.USER_ID, userId);
        intent.putExtra(MeetingConstant.USER_NAME, userName);

        intent.putExtra(MeetingConstant.MEETING_ROOM_VIDEO_CONFIG, videoConfig);
        return intent;
    }




}